package com.xr.redis.holder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <p>
 * 缓存服务被加载后注入ApplicationContext
 * </p>
 *
 * @author Arnold Yang
 * @since 2018-06-22
 */
public class SpringContextHolder implements ApplicationContextAware {

  private static ApplicationContext applicationContext = null;

  private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    logger.debug("注入ApplicationContext到" + SpringContextHolder.class.getName());
    SpringContextHolder.applicationContext = applicationContext;
  }

  public static <T> T getBean(String name) {
    if(applicationContext == null){
      throw new RuntimeException("无法访问ApplicationContext");
    }

    return (T) applicationContext.getBean(name);
  }

  public static <T> T getBean(Class<T> clazz){
    if(applicationContext == null){
      throw new RuntimeException("无法访问ApplicationContext");
    }

    return applicationContext.getBean(clazz);
  }
}
